package com.qixin.modules.eaApplication.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaApplication.entity.EaBusinessPerDtl;
import com.qixin.modules.eaApplication.service.IEaBusinessApplyService;
import com.qixin.modules.eaApplication.service.IEaBusinessPerDtlService;
import com.qixin.modules.eaApplication.vo.EaBusinessApplyPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* @Description: 出差申请单
* @Author: qixin-boot
* @Date:   2021-07-02
* @Version: V1.0
*/
@Api(tags="app出差申请单")
@RestController
@RequestMapping("/app/api/eaBusinessApply")
@Slf4j
public class ApiEaBusinessApplyController {
    @Autowired
    private IEaBusinessApplyService eaBusinessApplyService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    @Autowired
    private IEaBusinessPerDtlService eaBusinessPerDtlService;





    /**
     *   添加
     *
     * @param eaBusinessApplyPage
     * @return
     */
    @AutoLog(value = "出差申请单-添加")
    @ApiOperation(value="出差申请单-添加", notes="出差申请单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaBusinessApplyPage eaBusinessApplyPage) {
        EaBusinessApply eaBusinessApply = new EaBusinessApply();
        BeanUtils.copyProperties(eaBusinessApplyPage, eaBusinessApply);

        // update-begin-Autor: wmf date: 2022-02-08 11:42 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        if (StringUtils.isNotBlank(eaBusinessApply.getParentId())){
            jsonObj.put("prefix","CCBG");
        }else{
            jsonObj.put("prefix","CCSQ"); // 编码前缀
        }
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaBusinessApply.setBillNo(result.toString());

        // update-end-Autor: wmf date: 2022-02-08 11:42 for: 生成单据编号

        // 设置单据的状态为未提交
        eaBusinessApply.setState(0);
        eaBusinessApplyService.saveMain(eaBusinessApply, eaBusinessApplyPage.getEaBusinessPerDtlList());
        //update-begin-Autor：wjb 2022-02-07  for 返回主表、子表数据给前端
        EaBusinessApplyPage resultPage = new EaBusinessApplyPage();
        BeanUtils.copyProperties(eaBusinessApply,resultPage);
        //update-begin-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        if(eaBusinessApplyPage.getEaBusinessPerDtlList() != null && eaBusinessApplyPage.getEaBusinessPerDtlList().size() > 0){
            for (EaBusinessPerDtl eaBusinessPerDtl : eaBusinessApplyPage.getEaBusinessPerDtlList()) {
                NcPersonnel ncPersonnel = ncPersonnelService.getById(eaBusinessPerDtl.getPersonnel());
                if(ncPersonnel != null){
                    eaBusinessPerDtl.setPersonnelName(ncPersonnel.getName());
                }
            }
        }
        //update-end-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        resultPage.setEaBusinessPerDtlList(eaBusinessApplyPage.getEaBusinessPerDtlList());
        //update-end-Autor：wjb 2022-02-07  for 返回主表、子表数据给前端

        return Result.OK(resultPage);
    }

//    /**
//     * 编辑出差申请单信息
//     *
//     * @param eaBusinessApplyPage
//     * @return
//     */
//    @AutoLog(value = "出差申请单信息-编辑")
//    @ApiOperation(value="出差申请单信息-编辑", notes="出差申请单信息-编辑")
//    @PostMapping(value = "/edit")
//    public Result<?> edit(@RequestBody EaBusinessApplyPage eaBusinessApplyPage) {
//        EaBusinessApply eaBusinessApply = new EaBusinessApply();
//        BeanUtils.copyProperties(eaBusinessApplyPage, eaBusinessApply);
//        EaBusinessApply eaBusinessApplyEntity = eaBusinessApplyService.getById(eaBusinessApply.getId());
//        if(eaBusinessApplyEntity==null) {
//            return Result.error("未找到对应数据");
//        }
//
//        //判断单据是否已经被提交
//        EaBusinessApply eaBusinessApply1 = eaBusinessApplyService.getById(eaBusinessApplyPage.getId());
//        String status = EmptyUtil.checkNull(eaBusinessApply1.getState());   //当状态为1审批中,2已审批时,提示单据状态已变更,请刷新
//        if(status.equals("1") || status.equals("2")){
//            return Result.error("单据状态已变更,请刷新");
//        }
//
//        eaBusinessApply.setSaveType("add");    //保存
//        Map<String,Object> returnMap = eaBusinessApplyService.updateMain(eaBusinessApply,eaBusinessApplyPage.getEaBusinessPerDtlList());
//
//        if(returnMap.get("code").equals("-1")){
//            return Result.error(EmptyUtil.checkNull(returnMap.get("message")));
//        }else{
//            returnMap.remove("code");
//            returnMap.remove("message");
//            return Result.OK(returnMap);
//        }
//    }

    /**
     *  编辑
     *
     * @param eaBusinessApplyPage
     * @return
     */
    @ApiOperation(value="出差申请单-编辑", notes="出差申请单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaBusinessApplyPage eaBusinessApplyPage) {
        EaBusinessApply eaBusinessApply = new EaBusinessApply();
        BeanUtils.copyProperties(eaBusinessApplyPage, eaBusinessApply);
        EaBusinessApply eaBusinessApplyEntity = eaBusinessApplyService.getById(eaBusinessApply.getId());
        if(eaBusinessApplyEntity==null) {
            return Result.error("未找到对应数据");
        }
        eaBusinessApplyService.updateMain(eaBusinessApply, eaBusinessApplyPage.getEaBusinessPerDtlList());
        //update-begin-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        if(eaBusinessApplyPage.getEaBusinessPerDtlList() != null && eaBusinessApplyPage.getEaBusinessPerDtlList().size() > 0){
            for (EaBusinessPerDtl eaBusinessPerDtl : eaBusinessApplyPage.getEaBusinessPerDtlList()) {
                NcPersonnel ncPersonnel = ncPersonnelService.getById(eaBusinessPerDtl.getPersonnel());
                if(ncPersonnel != null){
                    eaBusinessPerDtl.setPersonnelName(ncPersonnel.getName());
                }
            }
        }
        //update-end-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        return Result.OK(eaBusinessApplyPage);
    }

//    /**
//     * 查询出差申请单信息列表
//     *
//     * @param listPageVo
//     * @return Result
//     */
//    @ApiOperation(value="出差申请单信息列表-查询", notes="出差申请单信息列表-查询")
//    @PostMapping(value = "/list")
//    public Result<?> list(@RequestBody ListPageVo listPageVo) {
//        Map<String,Object> resutlList = eaBusinessApplyService.list(listPageVo);
//        return Result.OK(resutlList);
//    }

    /**
    * @Description app关联申请单列表
    * @author  wujinbiao
    * @date 2022/2/17
    * @param[ keyword, pageNo, pageSize, req]
    * @return org.jeecg.common.api.vo.Result<?>
    */

    @ApiOperation(value="app出差申请单-关联报销单查询列表", notes="app出差申请单-关联报销单查询列表")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
                                   @RequestParam(name="keyword", required = false) String keyword,
                                   @RequestParam(name="userid", required = false) String userid,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<EaBusinessApply> param = new QueryWrapper<>();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 是当前用户创建的单据,并且审批通过 过滤已被变更的单据
        param.eq("create_by",user.getId()).eq("state",2).eq("if_changed",0);
        // 过滤被报销的出差申请单
        param.and(
                wrapper -> wrapper.isNull("ea_travel_id").or().eq("ea_travel_id","")
        );
        // 判断是否是代理报销
        if (StringUtils.isNotBlank(userid)){
            param.eq("person_id", userid);
        }
        // 单据编号，事由模糊查询
        if (StringUtils.isNotBlank(keyword)){
            param.and(
                p->
                p.like("bill_no",keyword).or().like("explain_str",keyword)
            );
        }

        Page<EaBusinessApply> page = new Page<EaBusinessApply>(pageNo, pageSize);
        IPage<EaBusinessApply> pageList = eaBusinessApplyService.page(page, param);
        //add-begin-by wujinbiao for 返回申请人中文名称
        List<EaBusinessApply> records = pageList.getRecords();
        for (EaBusinessApply eaBusinessApply1: records) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApply1.getPersonId());
            if(ncPersonnel != null){
                eaBusinessApply1.setPersonIdName(ncPersonnel.getName());
            }
        }
        //add-end-by wujinbiao for 返回申请人中文名称
        return Result.OK(pageList);
    }


//    /**
//     * 查询出差申请单详情
//     *
//     * @param idVo
//     * @return
//     */
//    @ApiOperation(value="出差申请单详情-查询", notes="出差申请单详情-查询")
//    @PostMapping(value = "/selectById")
//    public Result<?> selectById(@RequestBody IdVo idVo) {
//        String id = idVo.getId();
//        EaBusinessApply eaBusinessApply = eaBusinessApplyMapper.selectById(id);
//        if(eaBusinessApply==null) {
//            return Result.error("未找到对应数据");
//        }
//        Map<String, Object> resutlList = eaBusinessApplyService.selectById(id);
//        return Result.OK(resutlList);
//    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出差申请单-通过id查询")
    @ApiOperation(value="出差申请单-通过id查询", notes="出差申请单-通过id查询")
    @GetMapping(value = "/selectById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {

        EaBusinessApplyPage eaBusinessApplyPage = new EaBusinessApplyPage();
        EaBusinessApply eaBusinessApply = eaBusinessApplyService.getById(id);
        if(eaBusinessApply==null) {
            return Result.error("未找到对应数据");
        }
        //update-begin-by wujinbiao for 详情返回申请人名称
        if(StringUtils.isNotBlank(eaBusinessApply.getPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApply.getPersonId());
            eaBusinessApply.setPersonIdName(ncPersonnel.getName());
        }
        //update-end-by wujinbiao for 详情返回申请人名称
        BeanUtils.copyProperties(eaBusinessApply,eaBusinessApplyPage);
        //添加出行人员明细
        List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
        //update-begin-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        if(eaBusinessPerDtlList != null && eaBusinessPerDtlList.size() > 0){
            for (EaBusinessPerDtl eaBusinessPerDtl : eaBusinessPerDtlList) {
                NcPersonnel ncPersonnel = ncPersonnelService.getById(eaBusinessPerDtl.getPersonnel());
                if(ncPersonnel != null){
                    eaBusinessPerDtl.setPersonnelName(ncPersonnel.getName());
                }
            }
        }
        //update-end-by：wjb 2022-02-07 16:57  for 返回子表出差申请人中文
        eaBusinessApplyPage.setEaBusinessPerDtlList(eaBusinessPerDtlList);
        return Result.OK(eaBusinessApplyPage);
    }

//    /**
//     * 通过id删除出差申请单
//     *
//     * @param idVo
//     * @return
//     */
//    @AutoLog(value = "出差申请单信息-通过id删除")
//    @ApiOperation(value="出差申请单信息-通过id删除", notes="出差申请单信息-通过id删除")
//    @PostMapping(value = "/delete")
//    public Result<?> delete(@RequestBody IdVo idVo) {
//        String id = idVo.getId();
//        Map<String,Object> returnMap = eaBusinessApplyService.delMain(id);
//        if(returnMap.get("code").equals("0")){
//            return Result.OK("删除成功!");
//        }else{
//            String message = returnMap.get("message") != null ? returnMap.get("message").toString() : "";
//            return Result.error(message);
//        }
//    }

//    /**
//     *   通过id删除
//     *
//     * @param id
//     * @return
//     */
//    @AutoLog(value = "出差申请单-通过id删除")
//    @ApiOperation(value="出差申请单-通过id删除", notes="出差申请单-通过id删除")
//    @DeleteMapping(value = "/delete")
//    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//        eaBusinessApplyService.delMain(id);
//        return Result.OK("删除成功!");
//    }

    /**
     *   通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "出差申请单-通过id删除")
    @ApiOperation(value="出差申请单-通过id删除", notes="出差申请单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        QueryWrapper<EaBusinessApply> params = new QueryWrapper<>();
        params.eq("id",id);
        EaBusinessApply eaBusinessApply = eaBusinessApplyService.getOne(params);
        if (eaBusinessApply != null && eaBusinessApply.getState()>0){
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaBusinessApplyService.delMain(id);
        return Result.OK("删除成功!");
    }

//    /**
//     * 出差申请单审批/退回
//     *
//     * @param eaTaskVo
//     * @return
//     */
//    @AutoLog(value = "出差申请单审批/退回")
//    @ApiOperation(value="出差申请单审批/退回", notes="出差申请单审批/退回")
//    @PostMapping(value = "/audit")
//    public Result<?> edit(@RequestBody EaTaskVo eaTaskVo) {
//        Map<String,Object> returnMap = eaBusinessApplyService.audit(eaTaskVo);
//        return Result.OK(returnMap);
//    }

}
